phantom = require 'phantom'
fs = require('fs')
path = require "path"
os= require "os"
gridfs = require('../db/Gridfs')
fse = require 'fs-extra'

# FIXME - 1. 配置统一放到外部一个文件中，统一描述配置，然后require进来
#         2. 代码风格，缩进
#         3. 去掉硬编码的尺寸，路径等 - by alva

options =
  port: 3000
  hostname: "localhost"


templateShot =

  #保存截图
  saveScreenShot : (app_id,name,pageid,callback) ->
    phantom.create parameters: {"web-security" : false}, (ph) ->
      ph.createPage (page) ->
        page.set 'viewportSize', {width:270,height:484}
        page.open "http://#{options.hostname}:#{options.port}/apps/#{app_id}/#{pageid}.html", (status) ->
          #延时截图
          setTimeout  ->
            page.evaluate (-> document.title), (result) ->
              #文档加载完截图 evaluate
              console.log "截图成功 "
              imgPath="#{os.tmpdir()}/appbricks/#{name}.png"
              console.log imgPath
              page.render imgPath,{format: 'png', quality: '10'}, ->
                ph.exit()
                gridfs.upload imgPath,name,"image/png","appbricks"
                .then (obj) ->
                  imgPath ="/api/photos/appbricks/#{obj.filename}"
                  callback(imgPath)
                .catch (err) ->
                  callback(err)
          ,3000

  #删除截图
  delScreenShot : (imageid,callback) ->
    imgPath = "#{os.tmpdir()}/appbricks/#{imageid}"
    fse.remove imgPath, (err) ->
      return console.log (err) if err
      gridfs
      callback('success')



  #查询截图
  getScreenShot : (imageid) ->
    imgPath = "#{os.tmpdir()}/appbricks/#{imageid}"






module.exports = templateShot
